﻿using System;
using TechTalk.SpecFlow;
using System.Diagnostics;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection;

namespace Crap4Net.Specs
{
    [Binding]
    [Microsoft.VisualStudio.TestTools.UnitTesting.DeploymentItem(@"Crap4Net.Specs\TestData", "TestData")]
    public class MsBuildTaskSteps
    {
        const string MSBUILD = @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe";

        private string _BuildFile;

        
        [BeforeScenario]
        public void cleanup()
        {
            var path = Path.GetDirectoryName(Assembly.GetAssembly(this.GetType()).Location);
            Environment.CurrentDirectory = path;
            try
            {
                Directory.Delete("Results", true);
            }
            catch (DirectoryNotFoundException)
            {
                //ignore
            }
            Directory.CreateDirectory("Results");
        }

        [Given("Msbuild script (.*)$")]
        public void SetBuildScript(string buildFile)
        {
            Assert.IsTrue(File.Exists(buildFile));
            _BuildFile = buildFile;
        }

        [When("Running build Script")]
        public void RunScript()
        {
            using (var proc = new Process())
            {
                var info = new ProcessStartInfo();
                info.FileName = MSBUILD;
                info.Arguments = _BuildFile + " /t:CrapReport";
                info.RedirectStandardOutput = true;
                info.UseShellExecute = false;

                proc.StartInfo = info;
                proc.Start();

                proc.WaitForExit();
                Console.WriteLine(proc.StandardOutput.ReadToEnd());
                Assert.AreEqual(0, proc.ExitCode);
            }
        }

    }
}
